package com.example.schedulemanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.schedulemanager.pojo.Schedule;
import com.example.schedulemanager.pojo.TripMode;
import com.example.schedulemanager.service.ScheduleService;
import com.example.schedulemanager.service.TripModeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ScheduleManager {
    @Autowired
    public ScheduleService scheduleService;

    @Autowired
    public TripModeService tripModeService;


    @GetMapping("/list")
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String list(Model model, Schedule schedule) {
        QueryWrapper<Schedule> queryWrapper = new QueryWrapper<>();
        if (schedule.getTripModeId() != null && schedule.getTripModeId() > 0) {
            queryWrapper.eq("trip_mode_id", schedule.getTripModeId());
        }
        List<TripMode> tripModeId = tripModeService.list(null);
        List<Schedule> list = scheduleService.list(queryWrapper);
        model.addAttribute("tripModeId", tripModeId);
        model.addAttribute("list", list);

        return "list";
    }

    @GetMapping("/toAdd")
    public String toAdd(Model model) {

        List<TripMode> schedule = tripModeService.list();

        model.addAttribute("schedule", schedule);

        return "add";
    }

    @PostMapping("/add")
    public String add(Schedule schedule) {
        boolean save = scheduleService.save(schedule);
        if (save) {
            return "redirect:list";
        }
        return "add";
    }


    @PostMapping("/update")
    @ResponseBody
    public ResponseEntity<?> update(@RequestBody Schedule scheduleDto) {
        Schedule schedule=new Schedule();
        schedule.setStatus(scheduleDto.getStatus());
        schedule.setId(scheduleDto.getId());

        boolean update = scheduleService.updateById(schedule);
        if (update) {
            return ResponseEntity.ok("更新成功");
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新失败");
    }

}

